package com.superpeer.baseproject.utils;

import android.app.Activity;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.superpeer.baseproject.R;
import com.superpeer.baseproject.api.Url;
import com.superpeer.baseproject.bean.BaseBeanResult;
import com.superpeer.baseproject.bean.BaseObject;
import com.superpeer.baseproject.wight.ToastUitl;
import com.vector.update_app.HttpManager;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Request;

public class UpdateUtils {

    private Activity activity;
    private boolean showToast;

    private UpdateUtils(Activity activity){
        this.activity = activity;
    }

    public static UpdateUtils getInstance(Activity activity){
        UpdateUtils updateUtils = new UpdateUtils(activity);
        return updateUtils;
    }

    public void update(boolean showToast){
        this.showToast = showToast;
        toUpdate();
    }

    public void update(){
        this.showToast = false;
        toUpdate();
    }

    private void toUpdate(){
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(activity)
                //更新地址
                .setUpdateUrl(Url.IP + "/app/version/queryVersion")
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .setTopPic(R.mipmap.dialog_update_header_loading)
                .setThemeColor(activity.getResources().getColor(R.color.colorPrimary))
                .build()
                .checkNewApp(new UpdateCallback(){
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        BaseBeanResult baseBeanResult = new Gson().fromJson(json,BaseBeanResult.class);
                        BaseObject object = baseBeanResult.getData().getObject();
                        String update = "Yes";
                        boolean isConstraint = false;
                        if (AppUtils.getLocalVersion(activity) < Integer.parseInt(object.getVersionName())) {
                            update = "Yes";
                        }else{
                            update = "No";
                            if(showToast){
                                ToastUitl.showShort(activity,"您已经是最新版本");
                            }
                        }
                        if("1".equals(object.getIsNew())){
                            isConstraint = true;
                        }else{
                            isConstraint = false;
                        }
                        updateAppBean
                                //（必须）是否更新Yes,No
                                .setUpdate(update)
                                //（必须）新版本号，
                                .setNewVersion(object.getVersionNumber())
                                //（必须）下载地址
                                .setApkFileUrl(object.getVersionSrc())
                                //（必须）更新内容
                                .setUpdateLog(object.getVersionDescribe().replace("&","\r\n"))
                                //大小，不设置不显示大小，可以不设置
                                //.setTargetSize("")
                                //是否强制更新，可以不设置
                                .setConstraint(isConstraint);
                        return updateAppBean;
                    }
                });
    }

    class UpdateAppHttpUtil implements HttpManager{

        @Override
        public void asyncGet(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack) {
            OkHttpUtils.get()
                    .url(url)
                    .params(params)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            callBack.onError(e.getMessage());
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            callBack.onResponse(response);
                        }
                    });
        }

        @Override
        public void asyncPost(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack) {
            OkHttpUtils.post()
                    .url(url)
                    .params(params)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            callBack.onError(e.getMessage());
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            callBack.onResponse(response);
                        }
                    });
        }

        @Override
        public void download(@NonNull String url, @NonNull String path, @NonNull String fileName, @NonNull FileCallback callback) {
            OkHttpUtils.get()
                    .url(url)
                    .build()
                    .execute(new FileCallBack(path, fileName) {
                        @Override
                        public void inProgress(float progress, long total, int id) {
                            super.inProgress(progress, total, id);
                            callback.onProgress(progress, total);
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            callback.onError(e.getMessage());
                        }

                        @Override
                        public void onResponse(File response, int id) {
                            callback.onResponse(response);

                        }

                        @Override
                        public void onBefore(Request request, int id) {
                            super.onBefore(request, id);
                            callback.onBefore();
                        }
                    });
        }
    }
}
